<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 align="center">聊天室</h1>
<div align="center" style="width: 100%;height: 100%">
    <div style="border: solid 1px;color: red;height: 50px">
        <div style="display: inline-block;float: left">用户：<span id="username" th:text="${session.user}"></span></div>
        <div align="right" style="display: inline-block;float: right">离线、在线</div>
    </div>
    <div style="border: solid 1px;color: yellow">
        <div style="position: relative;border: solid 1px;color: blue;display:inline-block;float: left;width: 80%;height: 100%">
            <div>
                <textarea style="height: 200px;width: 100%;">聊天区域</textarea>
            </div>
            <div>
                <textarea style="height: 100px;width: 100%;" id="content">输入聊天记录</textarea>
                <input id="sendMsg" type="button" value="发送">
            </div>
        </div>
        <div style="position: relative;border: solid 1px;color: black;display:inline-block;float: right;width: 19%;height: auto">
            <div>
                <span>好友列表</span>
                <ul id="userList">
                </ul>
            </div>
            <div>
                <span>系统广播</span>
                <ul id="systemMsg">
                </ul>
            </div>
        </div>
    </div>
</div>
</body>
<script src="webjars/jquery/3.5.1/jquery.min.js">
</script>
<script>
    //跟websocket建立联系
    $(document).ready(function () {
        var username = $("#username").text();
        let webSocket = new WebSocket("ws://localhost:8080/chat");
        webSocket.onopen = function () {
            console.log("连接建立成功！");
        };
        webSocket.onmessage = function (event) {
            $("#userList").html("");
            $("#systemMsg").html("");
            console.log(event.data);
            let message = JSON.parse(event.data);
            for (let i = 0; i < message.toWhere.length; i++) {
                if (message.toWhere[i] !== username) {
                    $("#userList").append("<li>" + message.toWhere[i] + "</li>");
                }
                $("#systemMsg").append("<li>" + message.toWhere[i] + "上线了</li>");
            }
        };
        webSocket.onclose = function () {
            console.log("关闭连接");
        };
        webSocket.onerror = function (exception) {
            console.log(exception);
        };
        var toWhere = null;
        $("#userList").click(function () {
            toWhere = $("#userList").text().trim();
            alert(toWhere);
        });
        $("#sendMsg").click(function () {
            let content = $("#content").val();
            var messaage = {"isSystem": "false", "toUser": toWhere, "fromWhere": username, "content": content};
            webSocket.send(JSON.stringify(messaage));
        });
    });
</script>
</html>